import React, { useEffect, useState } from 'react'
import { Table, Space, Button, Modal, Form, Input } from 'antd';
import { useContext, useRef } from 'react';
import axios from 'axios';
import {
  DeleteOutlined,
  ExclamationCircleOutlined
 } from '@ant-design/icons';

const { confirm } = Modal;
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};


export default function Newscategory() {
  const [dataSource, setDataSource] = useState();

  useEffect(()=>{
    axios({
      url:'/categories',
    }).then(res =>
     setDataSource(res.data)
    )
  },[])

  const showConfirm = (item) => {
    confirm({
      title: '您确定要删除这一权限吗？',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        let list = dataSource;
          list = list.filter((data)=> data.id !== item.id)
          setDataSource(list);
          axios({
            url:`/rights/${item.id}`,
            method:'DELETE'
          })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render:(id) => (
        <b>{id}</b>
      )
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      onCell: (record) => ({
        record,
        editable: true,
        dataIndex: 'title',
        title: '栏目名称',
        handleSave,
      }),
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <Space size="middle">
          <Button danger shape="circle" icon={<DeleteOutlined />} size='small' onClick={()=>{
            showConfirm(item)
          }}/>
          </Space>
        )
      },
    },
  ];

  const handleSave = (record) => {
    console.log(record);
    setDataSource(dataSource.map(item =>{
      if(item.id === record.id){
        return {
          id: item.id,
          title: record.title,
          value: record.title,
        }
      }
      return item;
    }))
    axios.patch(`/categories/${record.id}`,{
      title:record.title,
      value:record.title
    })
  }
  
  return (
    <div>
      <Table dataSource={dataSource} 
             columns={columns} 
             pagination= {{
              pageSize:5
             }}
             components={components}
             rowKey = { item => item.id}
      />
    </div>
  )
}
